'''
Copyright (C) 2012 I&He, az@azijeon.com

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
'''
import inkex, os, simplestyle

from simplestyle import *
from copy import deepcopy

class SvgLinkProject():
    
    def __init__(self, plugin):
        
        self.plugin     = plugin 
        self.document   = plugin.document
        
        
    def create_project_layer(self):
        
        root = self.document.getroot()
        
        layer = inkex.etree.SubElement(root, 'g')
        layer.set(inkex.addNS('label', 'inkscape'), 'SVG Import Project')
        layer.set(inkex.addNS('groupmode', 'inkscape'), 'layer')
                               
        template = inkex.etree.parse(os.path.join(os.getcwd(), 'project.svg'));
        
        template = self.xpathSingle("//*[@id='azijeon-svglink-project']", template.getroot())
                        
        if template is not None:
        
            layer.append(template)
        
        return layer
    
    """ 
        Replaces all patterns that hlink to other patterns containing linked obejcts with the duplicate of the corresponding pattern.
        This is needed in order for the linked objects to be rendrered with respect to the patern transformations.
        
        TODO: Make it replace only patterns that transform the hlinked content.
    """
    def clear_linked_patterns(self):
        
        patterns_with_links = self.document.xpath('//svg:pattern[descendant::*[@data-embed]]', namespaces = inkex.NSS)
        
        for pattern in patterns_with_links:
            
            id = pattern.get('id', None)
            
            uses = self.document.xpath("//svg:pattern[@xlink:href='#%s']" % id, namespaces = inkex.NSS)
            
            for use in uses:
                
                href = str(inkex.addNS('href','xlink'))
                
                use.attrib.pop(href)
                
                id              = use.get("id")
                transform       = use.get('patternTransform')
                
                copy = deepcopy(pattern)
                copy.set('id', str(id))
                copy.set('patternTransform', str(transform))
                
                index = use.getparent().index(use)
                
                use.getparent().__setitem__(index, copy)              
               
                    
                
    
    
    def draw_imports(self):
        
        import_nodes = self.get_imports()
        
        
        if(import_nodes is None or len(import_nodes) < 1):
            return False
        
        g_imports = self.document.xpath("//*[@id='azijeon-svglink-project']//*[@id='imports-list']")
        
        if g_imports is not None and len(g_imports) > 0:
            
            g_imports = g_imports[0]
            self.clear_children(g_imports)
                                    
            count = 0
            
            for node in import_nodes:
                
                inode = inkex.etree.SubElement(g_imports, 'g');
                
                entry = self.draw_import_entry(node, count)
                entry.set('transform', "translate(0, %s)" % (count * 20 + 40))
                
                g_imports.append(entry)
                
                count += 1
         
        # Resize the background
        project_layer = self.get_project_layer()
        back = self.xpathSingle("//*[@id='Azijeon_SvgLink_ProjectBackground']", project_layer)
        
        back_height = str(160 + count * 15 + 50)
        
        back.set('height', back_height)
                
                            
            
    def get_imports(self, root = None):
        
        if(root is None):            
            root = self.document.getroot()
            embeds = root.xpath("//*[@class='Azijeon_SVG_Link']")
        else:
            root = deepcopy(root)
            embeds = root.xpath("//*[@class='Azijeon_SVG_Link']")
        
        
        return embeds
                
    
    def get_project_layer(self):
        
            node = self.document.xpath("//*[@id='azijeon-svglink-project']")
            
            if node is not None and len(node) > 0:
                node = node[0]
            else:
                return None           
            
            return node
            
    
    def draw_import_entry(self, node, number = None):
        
        entry = inkex.etree.Element('g')
        
        label = inkex.etree.SubElement(entry, inkex.addNS('text','svg'))
        
        text_style = {'font-size': 10}
        text_style = formatStyle(text_style)
        
        label.set('style', text_style)
        
        label.text = ''
        
        if(number is not None):
            label.text += "%s ) " % number
        
        label.text += "File:"
        
        id_value = inkex.etree.SubElement(entry, inkex.addNS('text','svg'))
        id_value.text = node.get('data-embed', '')
        id_value.set('data-target', node.get('id', ''))
        id_value.set('x', '50')
        id_value.set('style', text_style)
        
        return entry
    
    def clear_children(self, node):
        
        children = node.getchildren()
        
        for child in children:
            node.remove(child)
    
    def get_project_path(self):
        
        path_node = self.xpathSingle("//*[@id='svglink-project-path']", self.get_project_layer())
        
        if(path_node is not None):
            return path_node.text
        else:
            return ''
    
    def set_project_path(self, value):
        
        path_node = self.xpathSingle("//*[@id='svglink-project-path']", self.get_project_layer())
        
        self.clear_children(path_node)
        path_node.text = value        
    
    def xpathSingle(self, path, root = None):
        
        if(root is not None):
            document = root
        else:
            document = self.document
       
        try:
            retval = document.xpath(path)[0]        #, namespaces=NSS)[0]
        except:
            inkex.errormsg(_("No matching node for expression: %s") % path)
            retval = None
        return retval